package cc.vv.btpartyjob.activity.login

import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.view.View
import cc.vv.baselibrary.bean.base.BaseResponseObj
import cc.vv.baselibrary.bean.info.GeRenDataInfo
import cc.vv.baselibrary.global.UserInfoSharePreKey
import cc.vv.baselibrary.http.BaseHttpRequest
import cc.vv.baselibrary.util.LKPrefUtil
import cc.vv.baselibrary.util.LKToastUtil
import cc.vv.baselibrary.util.UserInfoManageUtil
import cc.vv.btpartyjob.R
import cc.vv.btpartyjob.activity.AddPartyRegisterActivity
import cc.vv.btpartyjob.activity.AppMainActivity
import cc.vv.btpartyjob.binder.AppMainTableHostDataBinder
import cc.vv.btpartyjob.delegate.LoginActivityDelegate
import cc.vv.btpartyjob.module.req.LoginRequestObj
import cc.vv.btpartyjob.module.resp.LoginResponseObj
import cc.vv.lkbasecomponent.http.LKHttp
import cc.vv.lkbasecomponent.http.lib.wrap.InterceptorWrap
import cc.vv.lkbasecomponent.util.LKStringUtil
import cc.vv.lklibrary.log.LogOperate
import cc.vv.mvp.activity.BaseActivityMVP
import cc.vv.mvp.binder.BaseDataBinder
import com.dawning.utiming.login.api.LoginApi
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException

/**
 * 登录界面
 * Created by chen.qi on 2018/10/24.
 */
class LoginActivity : BaseActivityMVP<LoginActivityDelegate>() {

    /**
     * 手机号
     */
    private var telMobile: String? = ""

    /**
     * 密码
     */
    private var telPsd: String? = ""


    override fun initData() {
        viewDelegate?.setPhone(UserInfoManageUtil.getPhone())
    }

    override fun bindEvenListener() {
        viewDelegate?.setOnClickListener(View.OnClickListener {

            val phone = viewDelegate.getPhoneNum()
            val psd = viewDelegate.getPassWord()

            if (!LKStringUtil.isPhoneNumber(phone)) {
                LKToastUtil.showToastShort("请输入正确的手机号码")
                return@OnClickListener
            }
            if (TextUtils.isEmpty(psd)) {
                LKToastUtil.showToastShort("密码不能为空")
                return@OnClickListener
            }
            login(phone, psd, true)
        }, R.id.tv_login_btn)
    }

    override fun getDelegateClass(): Class<LoginActivityDelegate> {
        return LoginActivityDelegate::class.java
    }

    override fun getDataBinder(): BaseDataBinder<*, *> {
        return AppMainTableHostDataBinder()
    }


    override fun initView(bundle: Bundle?) {
        super.initView(bundle)
        handler.sendEmptyMessage(10)
    }

    override fun onHandleMsg(msg: Message?) {
        super.onHandleMsg(msg)
        //设置全屏显示
        if (Build.VERSION.SDK_INT >= 21) {
            val decorView = window.decorView
            val option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            decorView.systemUiVisibility = option
            window.statusBarColor = Color.WHITE
        }
    }

    /**
     * 跳转到党员报到页面
     */
    private fun intentPartyReport() {
        val intent = Intent(this, AddPartyRegisterActivity::class.java)
        startActivity(intent)
        finish()
    }

    /** 跳转应用主界面*/
    private fun intentAppMainActivity() {
        val intent = Intent(this, AppMainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        startActivity(intent)
        finish()
    }


    /** 登录*/
    private fun login(mobile: String, passWord: String, isShowLoading: Boolean = false) {
        if (mobile.isNotEmpty() && passWord.isNotEmpty()) {
            UserInfoManageUtil.savePhone(mobile)
            val request = LoginRequestObj()
            telMobile = mobile
            telPsd = passWord
            request.account = mobile
            request.password = passWord
            BaseHttpRequest.postRequest(LoginApi.LoginInterface, request, LoginResponseObj::class.java, isShowLoading)
        }
    }

    override fun getData(obj: BaseResponseObj<*>?) {
        super.getData(obj)
        when (obj) {
            is LoginResponseObj -> {
                UserInfoManageUtil.savePhone(telMobile)
                UserInfoManageUtil.savePassword(telPsd)
                val userInfo = obj.data
                if (null != userInfo) {
                    UserInfoManageUtil.saveLogin(true)
                    UserInfoManageUtil.saveUserInfo(userInfo)

                    val userRole = userInfo.userRole
                    if (null != userRole) {
                        for (i in 0 until userRole.size) {
                            Log.e("lk_chen", "result角色==" + userRole[i].toString())
                        }
                    }

                    //保存的个人信息相关的所有数据
                    val geRen = GeRenDataInfo()
                    geRen.headPath = userInfo.resourceCtx + userInfo.curPartyMember?.photoPath
                    geRen.name = userInfo.userName
                    geRen.motto = userInfo.curPartyMember?.motto
                    geRen.totalLearnTime = userInfo.learningProfile?.hourAndMinute
                    geRen.todayLearn = userInfo.learningProfile?.todayHours
                    geRen.rank = userInfo.rank
                    geRen.mobile = userInfo.userAccount
                    geRen.sex = userInfo.curPartyMember?.sex
                    LKPrefUtil.putObject(UserInfoSharePreKey.GE_REN_DATA, geRen)


                    val partyReported = userInfo.partyMemberReported
                    LKPrefUtil.putBoolean(UserInfoSharePreKey.PARTY_IS_REPORT, partyReported)
                    if (!TextUtils.isEmpty(userInfo.token)) {
                        setHttpHead()
                    }
                    if (partyReported) {
                        intentPartyReport()
                    } else {
                        intentAppMainActivity()
                    }
                }
            }
        }
    }

    override fun getBadCode(obj: BaseResponseObj<*>?) {
        super.getBadCode(obj)
        if (null == obj) {
            return
        }
        when (obj.statusCode) {
            999 -> {
                LKToastUtil.showToastShort(obj.statusMessage)
            }
        }
    }


    /**
     * 设置token的请求头
     */
    private fun setHttpHead() {
        //okhttp添加请求头
        LKHttp.init().addIntercepter(object : InterceptorWrap() {
            @Throws(IOException::class)
            override fun interceptWrap(chain: Interceptor.Chain): Response {
                var request = chain.request()
                try {
                    val token = UserInfoManageUtil.getToken()
                    request = request.newBuilder()
                            .addHeader("X-Auth-Token", token).addHeader("platform", "app")
                            .build()
                } catch (e: NullPointerException) {
                    LogOperate.e("请求拦截器空指针", e)
                }

                return chain.proceed(request)

            }
        }, true)
    }


}